//
//  ZNWBNetworkManager+RequestMethods.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/4.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import Foundation

extension ZNWBNetworkManager {
    func statusesList(since_id: Int64 = 0, max_id: Int64 = 0, completion:@escaping(_ list: [[String: AnyObject]]?, _ isSuccessful: Bool) -> ()) {
        //homeUrl: https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.004GQL8GYTeVdDdf7b22858eI5c3cC
        //accessToken(访问令牌): 2.004GQL8GYTeVdDdf7b22858eI5c3cC
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": "\(since_id)", "max_id": "\(max_id)"]
        
        tokenRequest(URLString: url, parameters: params) { (json, isSuccess) in
            let result = json as? Dictionary<String, AnyObject>
            let statuses = result?["statuses"] as? [[String: AnyObject]]
            
            completion(statuses, isSuccess)
        }
    }
}

// MARK: - OAuth授权
extension ZNWBNetworkManager {
    func loadOAuthAccessToken(code: String, completion:@escaping (_ success: Bool) -> Void) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": ZNWBClientID,
                      "client_secret": ZNWBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": ZNWBRedirectURI]
        
        request(method: .POST, URLString: urlString, parameters: params) { (json, success) in
            
            //[:]：空字典，请求失败时，就不会用模型数据设置成功
            self.userAccount.yy_modelSet(with: (json as? [String: AnyObject]) ?? [:])
            
            // 闭包嵌套
            self.loadUserInfo(completion: { (dict) in
                // 设置用户头像与昵称信息
                self.userAccount.yy_modelSet(with: dict)
                
                // 将用户信息写入沙盒
                self.userAccount.saveToDisk()
                
                print(self.userAccount)
                
                completion(success)
            })
        }
    }
}

extension ZNWBNetworkManager {
    // 获取用户信息
    func loadUserInfo(completion: @escaping([String: AnyObject]) -> ()) {
        guard let uid = userAccount.uid
        else {
            return;
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let param = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: param) { (json, success) in
            completion((json as? [String: AnyObject]) ?? [:])
        }
    }
}
